package com.lcxw.hxzbadmin.common;

import com.alibaba.fastjson.JSONObject;
import com.lcxw.hxzbcommon.entity.ErrorCode;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import com.lcxw.hxzbcommon.common.RedisUtils;

public class YwpdInterceptor implements HandlerInterceptor {

    @Resource
    RedisUtils redisUtils;

    @Override //进入Controller之前执行该方法
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
        Object handler) throws Exception {
        //拦截的业务逻辑

        //先设置响应的状态码和返回数据格式
        response.setStatus(200);
        response.setContentType("application/json; charset=utf-8");

        Map<String, Object> map = new LinkedHashMap<>();

        //从请求中拿到adminName和token
        String bodyString = HttpHelper.getBodyString(request);
        JSONObject jsonToMap = JSONObject.parseObject(bodyString);
        if (null == jsonToMap){
            map.put("code", ErrorCode.PARAM_ERROR);
            map.put("desc", "body不能为空");
            JSONObject jsonObject = new JSONObject(map);
            response.getWriter().println(jsonObject);
            return false;
        }
        String adminName = jsonToMap.getString("adminName");
        String token = jsonToMap.getString("token");
        //判断是否携带adminName和token参数
        if (StringUtils.isEmpty(adminName) || StringUtils.isEmpty(token)) {
            map.put("code", ErrorCode.PARAM_ERROR);
            map.put("desc", "adminName 和 token不能为空。");
            JSONObject jsonObject = new JSONObject(map);
            response.getWriter().println(jsonObject);
            return false;
        }

        //从redis中获取token，判断登录状态与token校验，登录成功的话redis中会保存token
        String redisKey = "admin:" + adminName + ":token";
        if (!redisUtils.hasKey(redisKey)) {
            map.put("code", ErrorCode.NOT_EXIST);
            map.put("desc", "当前管理员登录未登录，或登录状态已过期。");
            JSONObject jsonObject = new JSONObject(map);
            response.getWriter().println(jsonObject);
            return false;
        }
        String tokenFromRedis = redisUtils.string_get(redisKey);
        if (StringUtils.isEmpty(tokenFromRedis) || !tokenFromRedis.equals(token)) {
            map.put("code", ErrorCode.HAS_CHANGED);
            map.put("desc", "该管理员已经在其他地方登录");
            JSONObject jsonObject = new JSONObject(map);
            response.getWriter().println(jsonObject);
            return false;
        }
        // TODO: 2020/7/4 错误码封装描述

        //继续提交请求，false 请求不提交了
        return true;

    }
}